<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <base href="/">
  <meta charset="utf-8">
  <title>我的订单</title>
  <link rel="stylesheet" href="orderConfirm/orderConfirm.css">
  <link rel="stylesheet" href="fonts/iconfont.css">
  <!-- 补充页面标题 -->
</head>
<body>
<div class="top-bar tonglan">
  <div class="top-nav-wrapper w">
    <div class="top-nav-left">

    </div>
    <div class="top-nav-right">
      <ul>
        <li><a href="page/index">首页</a></li><span></span>
        <li><a href="page/orderConfirm">我的订单</a></li> <span></span>
        <li><a href="page/cart">购物车</a></li> <span></span>
        <li class="lists-title"><a href="page/profile">个人中心</a></li><span></span>
        <li>
          <a href="#" id="logoutLink">退出登录</a>
        </li>
      </ul>
    </div>
  </div>
</div>
<div class="tonglan nav-bar">
  <div class="w">
    <div class="nav-logo">
      <img src="images/LOGO_2.png" alt="">
    </div>
    <div class="menu-wrapper">
      <div class="menu-wrapper-left">
        <ul id="categorylist">
          <li style="border-bottom: none;">
            <a href="page/index">首页</a>
          </li>
        </ul>
      </div>
      <div class="menu-wrapper-right">
      </div>
    </div>
  </div>
</div>
<div class="tonglan list-title-wrapper">
  <div class="w list-title">
        <span>
            <a href="page/index">首页</a>
        </span>
    <span>/产品订单/</span>
    <span>我的订单</span>
  </div>
</div>
<div class="w">
  <div class="list-center">
    <h3>我的订单</h3>
    <div class="list-center-container" id="order-list-container">
      <!-- 新增状态分类容器，原有订单列表结构改为状态分类展示 -->
      <div class="order-category">
        <h4>待付款</h4>
        <div class="order-items" data-status="待付款"></div>
      </div>
      <div class="order-category">
        <h4>已付款</h4>
        <div class="order-items" data-status="已付款"></div>
      </div>
      <div class="order-category">
        <h4>商家已发货</h4>
        <div class="order-items" data-status="商家已发货"></div>
      </div>
      <div class="order-category">
        <h4>已收货</h4>
        <div class="order-items" data-status="已收货"></div>
      </div>
      <div class="order-category">
        <h4>已完成订单</h4>
        <div class="order-items" data-status="已完成订单"></div>
      </div>
    </div>

    <!-- 订单详细内容展示区域 -->
    <div id="order-detail-container" style="display: none;">
      <h4>订单详细内容</h4>
      <div id="order-detail-content"></div>
    </div>
  </div>
</div>
<iframe src="footer/footer.html" frameborder="0"></iframe>

<!--<script src="orderConfirm/orderConfirm.js"></script>-->
<script src="layui/layui.all.js"></script>
<script type="text/html" id="categoryitem">
  <li>
    <a href="">电视</a>
    <div>
      <ul class="menu-main w">

      </ul>
    </div>
  </li>
</script>
<script type="text/html" id="categorychild">
  <li>
    <a href="">
      <img src="" alt="">
      <span></span>
    </a>
  </li>
</script>
<!-- 订单模板 -->
<script type="text/html" id="order-item-template">
  <div class="order-item" data-order-id="{{d.orderid}}">
    <div class="order-info" style="cursor: pointer;">
      <span class="order-id">订单编号: {{d.orderid}}</span>
      <span class="order-code">订单号: {{d.code}}</span>
      <span class="order-time">下单时间: {{d.ordertime}}</span>
      <span class="order-money">订单金额: {{d.money}}</span>
      <span class="order-status">订单状态: {{d.status}}</span>
      <span class="order-address">收货地址: {{d.address}}</span>
      <span class="order-isupset">是否上门安装: {{d.isupset === 0 ? '否' : '是'}}</span>
    </div>
  </div>
</script>
<!-- 订单详细内容模板 -->
<script type="text/html" id="order-detail-template">
  {{# for(var i = 0; i < d.orderInfos.length; i++) { }}
  <div class="product-item">
    <img src="{{d.orderInfos[i].imgurl}}" alt="{{d.orderInfos[i].productname}}" class="product-image" data-productid="{{d.orderInfos[i].productid}}" style="cursor: pointer;">
    <div class="product-info">
      <span class="product-name">商品名称: {{d.orderInfos[i].productname}}</span>
      <span class="product-category">商品类型: {{d.orderInfos[i].productcategory}}</span>
      <span class="product-price">商品单价价格: {{d.orderInfos[i].price}}</span>
      <span class="product-quantity">订货数量: {{d.orderInfos[i].quantity}}</span>
      <span class="product-description">商品描述: {{d.orderInfos[i].description}}</span>
    </div>
  </div>
  {{# } }}
  <!-- 根据订单状态来显示新增取消订单和支付按钮 -->
  {{# if (d.status === '待付款') { }}
  <div class="button-container">
    <button class="cancel-order-button" data-order-id="{{d.orderid}}">取消订单</button>
    <button class="pay-order-button" data-order-id="{{d.orderid}}">支付订单</button>
  </div>
  {{# } }}
  {{# if (d.status === '商家已发货') { }}
  <div class="button-container">
    <button class="received-order-button" data-order-id="{{d.orderid}}">已收货</button>
  </div>
  {{# } }}
  {{# if (d.status === '已收货') { }}
  <div class="button-container">
    <button class="complete-order-button" data-order-id="{{d.orderid}}">完成订单</button>
  </div>
  {{# } }}
  {{# if (d.status === '已完成订单') { }}
  <div class="button-container">
    <button class="delete-order-button" data-order-id="{{d.orderid}}">删除订单</button>
  </div>
  {{# } }}
</script>
<script>
  const $ = layui.$;
  let allOrders = [];

  // 父级分类下拉二级分类事件
  $.ajax({
    url: 'category/list',
    data: { id: -1 },
    success: function (result) {
      let data = result.data;
      console.log(data);

      // 筛选出 pid 为 -1 的父级分类
      const parentCategories = data.filter(item => item.pid === -1);

      parentCategories.forEach((parent) => {
        let item = $("#categoryitem").text();
        let $item = $(item);
        $item.children("a").text(parent.categoryname);
        $item.children("a").attr("href", `page/list?category=${parent.categoryname}`);
        let $ul = $item.find("ul");

        // 发起请求获取子分类
        $.ajax({
          url: "category/getChildren",
          data: { id: parent.categoryid },
          success: function (res) {
            for (let j = 0; j < res.length; j++) {
              let childtext = $("#categorychild").text();
              let $child = $(childtext);
              $child.find("span").text(res[j].categoryname);
              $child.find("img").attr("src", res[j].imgurl);
              $child.find("a").attr("href", `page/list?category=${res[j].categoryname}`);
              $ul.append($child);
            }
          },
          error: function (error) {
            console.error(`获取 ${parent.categoryname} 的子分类失败:`, error);
          }
        });

        $("#categorylist").append($item);
      });
    },
    error: function (error) {
      console.error('获取分类列表失败:', error);
    }
  });

  // 获取订单数据
  function getOrders() {
    $.ajax({
      url: 'order/list',
      success: function (result) {
        console.log('从后端获取到的订单数据:', result);
        if (result && result.data) {
          allOrders = result.data;
          const orderPromises = allOrders.map(order => {
            return new Promise((resolve, reject) => {
              if (order.addressid) {
                // 根据 addressid 获取地址信息，调用后端 getaddressbyid 接口
                $.ajax({
                  url: `address/getaddressbyid?id=${order.addressid}`,
                  success: function (addressResult) {
                    console.log("获取的地址信息",addressResult);
                    if (addressResult.data && typeof addressResult.data.address === 'string') {
                      order.address = addressResult.data.address;
                    } else {
                      order.address = '未找到地址信息';
                    }
                    resolve(order);
                  },
                  error: function (error) {
                    console.error('获取地址信息失败:', error);
                    order.address = '获取地址信息失败';
                    resolve(order);
                  }
                });
              } else {
                order.address = '未提供地址 ID';
                resolve(order);
              }
            });
          });

          Promise.all(orderPromises).then(updatedOrders => {
            renderOrders(updatedOrders);
          });
        } else {
          console.error('返回的数据格式不正确:', result);
          layer.msg('返回的数据格式不正确，请稍后重试', { icon: 2 });
        }
      },
      error: function (error) {
        console.error('获取订单列表失败:', error);
        layer.msg('获取订单列表失败，请稍后重试', { icon: 2 });
      }
    });
  }

  function renderOrders(orders) {
    const container = $('#order-list-container');
    container.empty();

    // 状态分类配置
    const statusConfig = [
      { status:'待付款', title: '待付款', class: 'unpaid' },
      { status: '已付款', title: '已付款', class: 'paid' },
      { status: '商家已发货', title: '商家已发货', class: 'shipped' },
      { status:  '已收货', title: '已收货', class: 'received' },
      { status: '已完成订单', title: '已完成订单', class: 'completed' }
    ];

    // 初始化分类容器
    statusConfig.forEach(config => {
      container.append(`
      <div class="order-category ${config.class}">
        <h4>${config.title}</h4>
        <div class="order-items" data-status="${config.status}"></div>
      </div>
    `);
    });

    // 分组订单数据
    const ordersByStatus = {};
    statusConfig.forEach(config => {
      ordersByStatus[config.status] = [];
    });
    orders.forEach(order => {
      const status = order.status;
      if (ordersByStatus.hasOwnProperty(status)) {
        ordersByStatus[status].push(order);
      }
    });

    // 填充每个分类容器
    statusConfig.forEach(config => {
      const target = $(`.order-items[data-status="${config.status}"]`);
      const ordersInCategory = ordersByStatus[config.status] || [];

      if (ordersInCategory.length === 0) {
        target.html('<p class="no-orders">当前没有相关订单</p>');
        return;
      }

      const template = $('#order-item-template').text();
      const render = layui.laytpl(template);

      ordersInCategory.forEach(order => {
        // 格式化时间
        const formattedTime = new Date(order.ordertime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });

        // 构造模板数据
        const orderData = {
          ...order,
          ordertime: formattedTime,
          status: config.title // 显示状态文本
        };

        target.append(render.render(orderData));
      });
    });

    // 事件绑定（保持原有逻辑）
    $('#order-list-container')
            .off('click', '.order-item')
            .on('click', '.order-item', function() {
              const orderId = $(this).data('order-id');
              showOrderDetail(orderId);
            });
  }

  // 显示订单详细内容
  function showOrderDetail(orderId) {
    layer.closeAll(); // 关闭所有已存在的弹窗
    console.log('传入的订单 ID:', orderId);
    $.ajax({
      url: `order/info/${orderId}`,
      success: function (result) {
        console.log("data中内容", result);
        if (result.code === 200) {
          const orderInfos = result.data;
          const orderDetailPromises = orderInfos.map(item => {
            return new Promise((resolve, reject) => {
              // 调用获取商品信息的接口
              $.ajax({
                url: `product/getproduct`,
                data: { id: item.productid },
                success: function (productResult) {
                  if (productResult.code === 0) {
                    const product = productResult.data;
                    // 将商品信息合并到订单信息中
                    const combinedItem = {
                      ...item,
                      productname: product.productname,
                      productcategory: product.productcategory,
                      price: product.price,
                      description: product.description,
                      imgurl: product.imgurl,
                      quantity: item.quantity
                    };
                    resolve(combinedItem);
                  } else {
                    reject(new Error('获取商品信息失败'));
                  }
                },
                error: function (error) {
                  reject(error);
                }
              });
            });
          });
          // 获取订单状态
          const orderStatus = allOrders.find(order => order.orderid === parseInt(orderId)).status;

          // 等待所有商品信息请求完成
          Promise.all(orderDetailPromises)
                  .then(combinedOrderInfos => {
                    const template = $('#order-detail-template').text();
                    const render = layui.laytpl(template);
                    const html = render.render({ orderInfos: combinedOrderInfos, orderid: orderId, status: orderStatus });

                    // 弹出对话框显示订单详情
                    const layerIndex = layer.open({
                      type: 1,
                      title: '订单详细内容',
                      content: `<div class="order-detail-dialog">${html}</div>`,
                      area: ['800px', '600px'],
                      scrollbar: false
                    });

                    // 绑定商品图片点击事件
                    $('.order-detail-dialog').on('click', '.product-image', function () {
                      const productid = $(this).data('productid');
                      window.location.href = `page/detail?productid=${productid}`;
                    });
                  })
                  .catch(error => {
                    console.error('获取商品信息失败:', error);
                    layer.msg('获取商品信息失败，请稍后重试', { icon: 2 });
                  });
        } else {
          console.error('获取订单详细内容失败:', result.msg);
          layer.msg('获取订单详细内容失败，请稍后重试', { icon: 2 });
        }
      },
      error: function (error) {
        console.error('获取订单详细内容失败:', error);
        layer.msg('获取订单详细内容失败，请稍后重试', { icon: 2 });
      }
    });
  }

  // 绑定取消订单按钮点击事件
  $(document).on('click', '.cancel-order-button', function () {
    const orderId = $(this).data('order-id');
    console.log('获取到的订单 ID:', orderId);
    layer.confirm('确定要取消该订单吗？', {
      btn: ['确定', '取消']
    }, function () {
      $.ajax({
        url: 'order/delete',
        method: 'POST',
        data: { id: orderId },
        success: function (result) {
          if (result.code === 200) {
            getOrders();
            layer.closeAll();
            layer.msg('订单取消成功', { icon: 1 });
          } else {
            layer.msg('订单取消失败: ' + result.msg, { icon: 2 });
          }
        },
        error: function (error) {
          console.error('取消订单失败:', error);
          layer.msg('取消订单失败，请稍后重试', { icon: 2 });
        }
      });
    }, function () {
      // 用户点击取消，不做任何操作
    });
  });

  // 绑定支付订单按钮点击事件
  $(document).on('click', '.pay-order-button', function () {
    const orderId = $(this).data('order-id');
    console.log('获取到的订单 ID:', orderId);
    layer.confirm('确定要支付该订单吗？', {
      btn: ['确定', '取消']
    }, function () {
      $.ajax({
        url: 'order/payment',
        method: 'POST',
        data: { id: orderId },
        success: function (result) {
          if (result.code === 200) {
            const qrcode = result.data;
            let qrLayer;
            qrLayer = layer.open({
              type: 1,
              title: '支付二维码',
              content: `<img src="data:png;base64,${qrcode}" alt="支付二维码">`,
              area: ['350px', '350px']
            });

            // 启动定时器检查订单状态
            let stateInterval = setInterval(function () {
              $.ajax({
                url: "order/getOrderstate",
                data: { id: orderId },
                success: function (result) {
                  if (result.data ==="已付款") {
                    layer.msg("支付成功", { icon: 1 });
                    clearInterval(stateInterval);
                    // 关闭二维码弹窗
                    layer.close(qrLayer);
                    setTimeout(function () {
                      // 跳转到订单页面
                      location.href = "page/orderConfirm";
                    }, 1800);
                  }
                },
                error: function (error) {
                  console.error('检查订单状态失败:', error);
                  // 出现异常时停止定时器
                  clearInterval(stateInterval);
                  layer.msg('检查订单状态失败，请稍后重试', { icon: 2 });
                }
              });
            }, 1500);

          } else {
            layer.msg('订单支付失败: ' + result.msg, { icon: 2 });
          }
        },
        error: function (error) {
          console.error('支付订单失败:', error);
          layer.msg('支付订单失败，请稍后重试', { icon: 2 });
        }
      });
    }, function () {
      // 用户点击取消，不做任何操作
    });
  });

  // 绑定已收货按钮点击事件
  $(document).on('click', '.received-order-button', function () {
    const orderId = $(this).data('order-id');
    console.log('获取到的订单 ID:', orderId);
    layer.confirm('确定该订单已收货吗？', {
      btn: ['确定', '取消']
    }, function () {
      $.ajax({
        url: 'order/updateStatus',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
          orderid: orderId,
          status: '已收货'
        }),
        success: function (result) {
          if (result.code === 200) {
            getOrders();
            layer.closeAll();
            layer.msg('订单状态更新为已收货', { icon: 1 });
          } else {
            layer.msg('订单状态更新失败: ' + result.msg, { icon: 2 });
          }
        },
        error: function (error) {
          console.error('更新订单状态失败:', error);
          layer.msg('更新订单状态失败，请稍后重试', { icon: 2 });
        }
      });
    }, function () {
      // 用户点击取消，不做任何操作
    });
  });

  // 绑定完成订单按钮点击事件
  $(document).on('click', '.complete-order-button', function () {
    const orderId = $(this).data('order-id');
    console.log('获取到的订单 ID:', orderId);
    layer.confirm('确定要完成该订单吗？', {
      btn: ['确定', '取消']
    }, function () {
      // 第一步：更新订单状态为已完成订单
      $.ajax({
        url: 'order/updateStatus',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
          orderid: orderId,
          status: '已完成订单'
        }),
        success: function (result) {
          if (result.code === 200) {
            // 第二步：获取订单详情中的商品信息
            $.ajax({
              url: `order/info/${orderId}`,
              success: function (orderInfoResult) {
                if (orderInfoResult.code === 200) {
                  const orderInfos = orderInfoResult.data;
                  const orderProducts = [];
                  orderInfos.forEach(item => {
                    orderProducts.push({
                      productid: item.productid,
                      quantity: item.quantity
                    });
                  });
                  // 第三步：发送请求更新商品的库存和销量
                  $.ajax({
                    url: 'product/updateStockAndSales',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(orderProducts),
                    success: function (updateResult) {
                      if (updateResult.code === 200) {
                        getOrders();
                        layer.closeAll();
                        layer.msg('订单状态更新为已完成订单，商品库存和销量更新成功', { icon: 1 });
                        location.reload();
                      } else {
                        layer.msg('商品库存和销量更新失败: ' + updateResult.msg, { icon: 2 });
                      }
                    },
                    error: function (error) {
                      console.error('更新商品库存和销量失败:', error);
                      layer.msg('更新商品库存和销量失败，请稍后重试', { icon: 2 });
                    }
                  });
                } else {
                  console.error('获取订单详细内容失败:', orderInfoResult.msg);
                  layer.msg('获取订单详细内容失败，请稍后重试', { icon: 2 });
                }
              },
              error: function (error) {
                console.error('获取订单详细内容失败:', error);
                layer.msg('获取订单详细内容失败，请稍后重试', { icon: 2 });
              }
            });
          } else {
            layer.msg('订单状态更新失败: ' + result.msg, { icon: 2 });
          }
        },
        error: function (error) {
          console.error('更新订单状态失败:', error);
          layer.msg('更新订单状态失败，请稍后重试', { icon: 2 });
        }
      });
    }, function () {
      // 用户点击取消，不做任何操作
    });
  });
  // 退出登录逻辑
  const logoutLink = document.getElementById('logoutLink');
  logoutLink.addEventListener('click', function (e) {
    e.preventDefault(); // 阻止默认的链接跳转行为
    // 弹出确认提示框
    if (confirm('确定要退出登录吗？')) {
      $.ajax({
        url: 'logout', // 后端退出登录的接口地址
        method: 'GET',
        success: function (response) {
          if (response.code === 200) {
            // 退出登录成功，给出提示并跳转到登录页面
            alert(response.msg);
            window.location.href = 'page/login';
          } else {
            // 退出登录失败，给出提示
            alert(response.msg);
          }
        },
        error: function (error) {
          console.error('退出登录失败:', error);
          alert('退出登录时发生错误，请稍后再试。');
        }
      });
    }
  });


  // 绑定删除订单按钮点击事件
  $(document).on('click', '.delete-order-button', function () {
    const orderId = $(this).data('order-id');
    console.log('获取到的订单 ID:', orderId);
    layer.confirm('确定要删除该订单吗？', {
      btn: ['确定', '取消']
    }, function () {
      $.ajax({
        url: 'order/delete',
        method: 'POST',
        data: { id: orderId },
        success: function (result) {
          if (result.code === 200) {
            getOrders();
            layer.closeAll();
            layer.msg('订单删除成功', { icon: 1 });
          } else {
            layer.msg('订单删除失败: ' + result.msg, { icon: 2 });
          }
        },
        error: function (error) {
          console.error('删除订单失败:', error);
          layer.msg('删除订单失败，请稍后重试', { icon: 2 });
        }
      });
    }, function () {
      // 用户点击取消，不做任何操作
    });
  });
  // 页面加载时获取订单数据
  getOrders();
</script>
</body>
</html>